package com.yyk.yykywd.mvvm.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.orhanobut.logger.Logger
import com.yyk.yykywd.*
import com.yyk.yykywd.aa.PieChartManager
import com.yyk.yykywd.base.BaseFragment
import com.yyk.yykywd.mvvm.adapter.DynamicBroadCastAdapter
import com.yyk.yykywd.mvvm.entity.HomeBean
import com.yyk.yykywd.mvvm.entity.HomeSearchBean
import com.yyk.yykywd.mvvm.event.RefreshHomeData
import com.yyk.yykywd.mvvm.view_model.BusinessViewModel
import com.yyk.yykywd.util.TimeUtil
import com.yyk.yykywd.util.ToAnotherActivity
import com.yyk.yykywd.util.ToastUtil
import kotlinx.android.synthetic.main.fragment_business.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 文件描述：
 * Created by guo on 2019-11-26.
 */
class BusinessFragment : BaseFragment() {
    private lateinit var viewModel: BusinessViewModel
    private lateinit var adapter: DynamicBroadCastAdapter
    private lateinit var statistics: HomeBean.Data.Count
    private lateinit var pieChartManager: PieChartManager
    private lateinit var pieChartManager1: PieChartManager
    override fun initData() {
        viewModel.getHome()
        viewModel.getSearchData(getTextString(tv_start_time), getTextString(tv_end_time))
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_business
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        viewModel = getFragmentViewModel(this, BusinessViewModel::class.java)
        viewModel.id = arguments?.getInt(ID).toString()

        rv.layoutManager = LinearLayoutManager(activity)
        adapter = DynamicBroadCastAdapter(requireActivity(), R.layout.item_dynamic_broadcast, viewModel.reports)
        rv.adapter = adapter
        //饼形图
        pieChartManager = PieChartManager(activity, pieChart)
        pieChartManager1 = PieChartManager(activity, pieChart_statistical)

        viewModel.colors.add(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        viewModel.colors.add(ContextCompat.getColor(requireActivity(), R.color.col_68c3d4))
        viewModel.colors.add(ContextCompat.getColor(requireActivity(), R.color.col_f5c161))
        viewModel.statisticsHospitalIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        viewModel.statisticsHospitalIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_56c83e))
        viewModel.statisticsHospitalIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_f5c161))
        viewModel.statisticsHospitalIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_68c3d4))
        if (viewModel.id == "0") {
            viewModel.statisticsHospitalIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_ea6b66))
        }
        viewModel.statisticsAgentIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        viewModel.statisticsAgentIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_56c83e))
        viewModel.statisticsAgentIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_f5c161))
//        viewModel.statisticsAgentIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_68c3d4))
        viewModel.statisticsAgentIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_3b889e))
        if (viewModel.id == "0") {
            viewModel.statisticsAgentIntegers.add(ContextCompat.getColor(requireActivity(), R.color.col_ea6b66))
        }
    }

    override fun setListener() {
        super.setListener()

        viewModel.search.observe(this, Observer<HomeSearchBean> {
            if (viewModel.selectedHospitalCustomer) {
                setResult()
            } else {
                setResult1()
            }
        })

        viewModel.home.observe(this, Observer<HomeBean> {
            adapter.notifyDataSetChanged()
            Logger.e(viewModel.reports.toString())
            if (viewModel.reports.size != 0) {
                loading_layout.visibility = View.GONE
                space1.visibility = View.GONE
            } else {
                loading_layout.visibility = View.VISIBLE
                loading_layout.showEmpty(R.mipmap.icon_zwsj, "暂无数据")
                space1.visibility = View.VISIBLE
            }

            val todayData = it.data.today_data
            tv_add_customer_hospital.text = todayData.hosaddcount.toString()
            tv_add_customer_agent.text = todayData.agentaddcount.toString()
            tv_sign_contract_hospital.text = todayData.hospactcount.toString()
            tv_sign_contract_agent.text = todayData.agentpactcount.toString()
            tv_install_hospital_num.text = todayData.inserthos.toString()
            val s = todayData.answer_money ?: "0"
            var i = ""
            if (s.toFloat() > 10000) {
                i = (s.toFloat() / 10000).toString()
                tv_unit2.text = "万元"
            } else {
                i = s.toFloat().toInt().toString()
                tv_unit2.text = "元"
            }
            tv_return_money_num.text = i

            statistics = viewModel.customerStatistics
            setAgentStatistic()

            srl.finishRefresh()
        })

        tv_more.setOnClickListener {
            ToAnotherActivity.toDynamicBroadcastActivity(requireActivity(), viewModel.id)
        }

        rl_hospital_customer1.setOnClickListener {
            setHospitalStatistic()
        }
        rl_agent_customer1.setOnClickListener {
            setAgentStatistic()
        }

        rl_hospital_customer2.setOnClickListener {
            viewModel.selectedHospitalCustomer = true
            setResult()
        }

        rl_agent_customer2.setOnClickListener {
            viewModel.selectedHospitalCustomer = false
            setResult1()
        }

        tv_start_time.setOnClickListener {
            showTimePicker(requireActivity(),
                    showYear = true,
                    showMonth = true,
                    showDay = true,
                    showHour = false,
                    showMinute = false,
                    showSecond = false,
                    startDate = viewModel.startDate,
                    endDate = viewModel.endDate,
                    pattern = TimeUtil.YYYY_MM_DD) {
                tv_start_time.text = it
            }
        }
        tv_end_time.setOnClickListener {
            showTimePicker(requireActivity(),
                    showYear = true,
                    showMonth = true,
                    showDay = true,
                    showHour = false,
                    showMinute = false,
                    showSecond = false,
                    startDate = viewModel.startDate,
                    endDate = viewModel.endDate,
                    pattern = TimeUtil.YYYY_MM_DD) {
                tv_end_time.text = it
            }
        }

        tv_search.setOnClickListener {
            if (getTextString(tv_start_time).isEmpty() && getTextString(tv_end_time).isEmpty()){
                ToastUtil.showShort("请选择查询时间")
                return@setOnClickListener
            }
            if (getTextString(tv_start_time).isEmpty()) {
                ToastUtil.showShort("请选择开始时间")
                return@setOnClickListener
            }
            if (getTextString(tv_end_time).isEmpty()) {
                ToastUtil.showShort("请选择结束时间")
                return@setOnClickListener
            }
            //前者大于后者 返回大于0 反之小于0
            val result: Int = compareDate(getTextString(tv_start_time),
                    getTextString(tv_end_time),
                    TimeUtil.YYYY_MM_DD)
            if (result > 0) {
                ToastUtil.showShort(requireActivity(), "结束时间需晚于开始时间")
                return@setOnClickListener
            }

            viewModel.getSearchData(getTextString(tv_start_time), getTextString(tv_end_time))
        }

        tv_all.setOnClickListener {
            reloadSearchData()
        }

        srl.setEnableLoadMore(false)
        srl.setOnRefreshListener {
            reloadData()
        }
    }

    private fun setHospitalStatistic() {
        tv_hospital_customer1.setTextColor(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        rl_hospital_customer1.setBackgroundResource(R.drawable.yyxz)
        tv_agent_customer1.setTextColor(ContextCompat.getColor(requireActivity(), R.color.black_33))
        rl_agent_customer1.setBackgroundResource(R.drawable.wxz)
        tv_potential_customer.text = "意向客户：" + statistics.hosaddcount
        tv_c_customer.text = "C类客户：" + statistics.choscount
        tv_sign_contract_customer.text = "签订合同客户：" + statistics.pactcount
        tv_install_complete.visibility = View.VISIBLE
        tv_install_complete.text = "安装完成：" + statistics.okcount
        tv_open_sea_customer.text = "公海客户：" + statistics.ghcount
        tv_receive_complete_customer.visibility = View.GONE
        if (viewModel.id == "0") {
            tv_open_sea_customer.visibility = View.VISIBLE
        } else {
            tv_open_sea_customer.visibility = View.GONE
        }
        pieChartManager.setData(viewModel.statisticsHospitalPielist,
                viewModel.statisticsHospitalIntegers,
                viewModel.hospitalCustomerSum.toString())
    }

    private fun setAgentStatistic() {
        tv_hospital_customer1.setTextColor(ContextCompat.getColor(requireActivity(), R.color.black_33))
        rl_hospital_customer1.setBackgroundResource(R.drawable.wxz)
        tv_agent_customer1.setTextColor(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        rl_agent_customer1.setBackgroundResource(R.drawable.yyxz)

        tv_receive_complete_customer.visibility = View.VISIBLE
        tv_potential_customer.text = "意向客户：" + statistics.dhosaddcount
        tv_c_customer.text = "C类客户：" + statistics.dchoscount
        tv_sign_contract_customer.text = "签订合同客户：" + statistics.dpactcount
        tv_install_complete.visibility = View.GONE
//            tv_install_complete.text = "待回款客户：" + statistics.dhkcount
        tv_receive_complete_customer.text = "回款完成客户：" + statistics.dmoneyokcount
        tv_open_sea_customer.text = "公海客户：" + statistics.dghcount
        if (viewModel.id == "0") {
            tv_open_sea_customer.visibility = View.VISIBLE
        } else {
            tv_open_sea_customer.visibility = View.GONE
        }
        pieChartManager.setData(viewModel.statisticsAgentPielist,
                viewModel.statisticsAgentIntegers,
                viewModel.agentCustomerSum.toString())
    }

    private fun setResult() {
        tv_hospital_customer2.setTextColor(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        rl_hospital_customer2.setBackgroundResource(R.drawable.yyxz)
        tv_agent_customer2.setTextColor(ContextCompat.getColor(requireActivity(), R.color.black_33))
        rl_agent_customer2.setBackgroundResource(R.drawable.wxz)
        cl_hospital.visibility = View.VISIBLE
        cl_agent.visibility = View.GONE
        tv_sign_site_num.text = viewModel.hospital.sitecount.toString()
        tv_install_site_num.text = viewModel.hospital.insertok.toString()
        tv_hint.text = "签约站点"
        tv_small_site.text = "小型站点：" + viewModel.hospital.hsmall
        tv_medium_site.text = "中型站点：" + viewModel.hospital.hcenter
        tv_large_site.text = "大型站点：" + viewModel.hospital.hbig

        pieChartManager1.setData(viewModel.hospitalPieList,
                viewModel.colors,
                viewModel.hospitalCustomerSum1.toString())
    }

    private fun setResult1() {
        tv_agent_customer2.setTextColor(ContextCompat.getColor(requireActivity(), R.color.col_5987ff))
        rl_agent_customer2.setBackgroundResource(R.drawable.yyxz)
        tv_hospital_customer2.setTextColor(ContextCompat.getColor(requireActivity(), R.color.black_33))
        rl_hospital_customer2.setBackgroundResource(R.drawable.wxz)
        cl_agent.visibility = View.VISIBLE
        cl_hospital.visibility = View.GONE
        if (viewModel.agent.getmoneycount.isNullOrEmpty()) {
            tv_total_num.text = "0"
        } else {
            tv_total_num.text = viewModel.agent.getmoneycount
        }
        tv_dhk_num.text = viewModel.agent.timemoney.toString()
        tv_hk_num.text = viewModel.agent.moneycount.toString()
        tv_dhk.text = viewModel.agent.nomoneycount.toString()
        tv_hint.text = "签订合同"
        tv_small_site.text = "小型站点：" + viewModel.agent.asmall
        tv_medium_site.text = "中型站点：" + viewModel.agent.acenter
        tv_large_site.text = "大型站点：" + viewModel.agent.abig

        pieChartManager1.setData(viewModel.agentPieList,
                viewModel.colors,
                viewModel.agentCustomerSum1.toString())
    }

    companion object {
        fun newInstance(id: Int): BusinessFragment {
            val args = Bundle()
            args.putInt(ID, id)
            val fragment = BusinessFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshHomeData(event: RefreshHomeData) {
        reloadData()
    }

    private fun reloadData() {
        viewModel.getHome()
        reloadSearchData()
    }

    private fun reloadSearchData(){
        tv_start_time.text = ""
        tv_end_time.text = ""
        viewModel.getSearchData(getTextString(tv_start_time), getTextString(tv_end_time))
    }
}